package Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import Entities.SaleResponseEntity;
import GUI.ReportsGUI;
import GUI.SaleResponsesReportGUI;
import GUI.cReportGUI;
import Server.RsWraper;
import Server.Tuple;

/**
 * The Class ReportsController.
 */
public class ReportsController{
	
	/** The r gui. */
	private ReportsGUI rGUI;
	
	/** The srr ent. */
	private SaleResponseEntity srrEnt;
	
	/** The prev. */
	private MarketingManagerController prev;
	
	/** The tuples. */
	private ArrayList<Tuple> tuples=new ArrayList<Tuple>();
	
	/**
	 * Instantiates a new reports controller.
	 *
	 * @param rGUI the r gui
	 */
	public ReportsController(ReportsGUI rGUI)
	{
		this.rGUI=rGUI;
		
		this.rGUI.addSaleResponseReportListener(new srrListener());
		this.rGUI.addCustomerCharaReportListener(new ccrListener());
		this.rGUI.addBackListener(new BackListener());
		srrEnt=new SaleResponseEntity();
		this.rGUI.setVisible(true);
	}
	
	/**
	 * The listener interface for receiving back events.
	 * The class that is interested in processing a back
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addBackListener<code> method. When
	 * the back event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see BackEvent
	 */
	class BackListener implements ActionListener
	{

		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			LoginController.mainWindow.setTitle("Marketing manager");
			LoginController.mainWindow.setContentPane(prev.getMarketingManagerGui());
			
		}
		
	}
	
	/**
	 * The listener interface for receiving srr events.
	 * The class that is interested in processing a srr
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addsrrListener<code> method. When
	 * the srr event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see srrEvent
	 */
	class srrListener implements ActionListener,Observer,Validate
	{
		
		/** The operation. */
		private int operation=0;
		
		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			if(validateInput())
			{
				ClientController.setObserver(this);
				String query= "SELECT count(sid) as amountofcustomers FROM servesinsale WHERE servesinsale.sid = '"+srrEnt.getSid()+"'";
				try {
					ClientController.observableClient.sendToServer(query);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			
		}

		/* (non-Javadoc)
		 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
		 */
		@Override
		public void update(Observable o, Object arg) {
			String msg=(String)arg.toString();
			String query;
			if(operation==0)
			{
				if(!msg.equals("empty query"))
				{
				srrEnt.setAmountOfCustomers(Integer.parseInt((((RsWraper)arg).getRows()).get(0).get("AMOUNTOFCUSTOMERS")));
				if(srrEnt.getAmountOfCustomers()==0)
				{
					rGUI.displayWarningMessage("Sale id does not exists, please choose another one");	
				}
				else{
				query="SELECT sum(phonetime) as sumoftimeonphone "
						+ "FROM customersresponsestooffer as c "
						+ "WHERE c.sid = '"+srrEnt.getSid()+"'";
				try {
					ClientController.observableClient.sendToServer(query);
					operation=1;
				} catch (IOException e) {e.printStackTrace();
				}
				}
				}
				else
					rGUI.displayWarningMessage("Sale id does not exists, please choose another one");	

			}
			else if(operation==1)
			{
				if(!msg.equals("empty query"))
				{
					int time=Integer.parseInt((((RsWraper)arg).getRows()).get(0).get("SUMOFTIMEONPHONE"));
					int h=time/3600;
					int m=(time/60)%60;
					int s=time % 60;
					String sTime = h+":"+m+":"+s;
					Date date;
					try {
						date = new SimpleDateFormat("HH:mm:ss").parse(sTime);
						String newString = new SimpleDateFormat("HH:mm:ss").format(date); 
						srrEnt.setSumOfTimeOnPhone(newString);
					} catch (ParseException e) {	e.printStackTrace();	}
					
			
				}
				else
				{
					srrEnt.setSumOfTimeOnPhone("00:00:00");	
				}
				query="SELECT count(sid) as saleevents "
						+ "FROM customersresponsestooffer as c "
						+ "WHERE c.sid = '"+srrEnt.getSid()+"' AND c.customerResponse = 'YES'";
				try {
					ClientController.observableClient.sendToServer(query);
					operation=2;
				} catch (IOException e) {e.printStackTrace();
				}
				
				
			}
			else if(operation==2)
			{
				if(!msg.equals("empty query"))
				srrEnt.setEvents(Integer.parseInt((((RsWraper)arg).getRows()).get(0).get("SALEEVENTS")));
				else
					srrEnt.setEvents(0);
				query="SELECT c.cid,c.description "
						+ "FROM customersresponsestooffer as c "
						+ "WHERE c.sid = '"+srrEnt.getSid()+"' AND c.customerresponse = 'NO' ";
				try {
					ClientController.observableClient.sendToServer(query);
					operation=3;
				} catch (IOException e) {e.printStackTrace();
				}
			}
			else if(operation==3)
			{
				ArrayList<String> res= new ArrayList<String>();
				if(!msg.equals("empty query"))
				{
				ArrayList<Tuple> tuples= ((RsWraper)arg).getRows();
				for(int i=0;i<tuples.size();i++)
				res.add(tuples.get(i).get("CID")+","+tuples.get(i).get("DESCRIPTION"));
				}
				else
					res.add("0,no comments");
				srrEnt.setResponses(res);
				SaleResponsesReportGUI srrGUI=new SaleResponsesReportGUI();
				new SaleResponsesReportController(srrGUI,srrEnt).setPrev(ReportsController.this);
				LoginController.mainWindow.setContentPane(srrGUI);	
				operation=0;
			
			}
			
		}

		/* (non-Javadoc)
		 * @see Controllers.Validate#validateInput()
		 */
		@Override
		public boolean validateInput() {
			srrEnt.setSid(rGUI.getSidTf().getText());
			if(srrEnt.getSid().equals(""))
			{
				rGUI.displayWarningMessage("Please enter sale id");
				return false;
			}
			return true;
		}
		
	}
	
	/**
	 * The listener interface for receiving ccr events.
	 * The class that is interested in processing a ccr
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addccrListener<code> method. When
	 * the ccr event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see ccrEvent
	 */
	class ccrListener implements ActionListener,Observer
	{
		
		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			ClientController.setObserver(ccrListener.this);
			String query = "SELECT DISTINCT customers.cid,users.name"
					+ " FROM customers,authorizations,users"
					+ " WHERE customers.cid = authorizations.cid AND customers.cid=users.uid"
					+ " ORDER BY customers.importancerank+authorizations.interestlevel";
			try {
				ClientController.observableClient.sendToServer(query);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}

		/* (non-Javadoc)
		 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
		 */
		@Override
		public void update(Observable o, Object arg) {
			// TODO Auto-generated method stub
			if(arg.toString().equals("empty query")||arg.toString().equals("error"))
			{
				rGUI.displayWarningMessage("This information is not exists");
			}
			else
			{
				
				tuples.addAll(((RsWraper)arg).getRows());
				String[] cReportList = new String[tuples.size()];
				for(int i=0;i<cReportList.length;i++)
				{
					cReportList[i]=tuples.get(i).get("CID")+","+tuples.get(i).get("NAME");
				}
				tuples=new ArrayList<Tuple>();
				cReportGUI crGUI = new cReportGUI();
				crGUI.getCReportList().setListData(cReportList);
				new cReportController(crGUI).setPrev(ReportsController.this);
				LoginController.mainWindow.setContentPane(crGUI);
			}
		
		}
		
	}
	
	/**
	 * Sets the prev.
	 *
	 * @param marketingManagerController the new prev
	 */
	public void setPrev(MarketingManagerController marketingManagerController) {
		prev=marketingManagerController;
	}

	/**
	 * Gets the r gui.
	 *
	 * @return the r gui
	 */
	public ReportsGUI getrGUI() {
		return rGUI;
	}

	/**
	 * Sets the r gui.
	 *
	 * @param rGUI the new r gui
	 */
	public void setrGUI(ReportsGUI rGUI) {
		this.rGUI = rGUI;
	}

	/**
	 * Gets the srr ent.
	 *
	 * @return the srr ent
	 */
	public SaleResponseEntity getSrrEnt() {
		return srrEnt;
	}

	/**
	 * Sets the srr ent.
	 *
	 * @param srrEnt the new srr ent
	 */
	public void setSrrEnt(SaleResponseEntity srrEnt) {
		this.srrEnt = srrEnt;
	}

	/**
	 * Gets the prev.
	 *
	 * @return the prev
	 */
	public MarketingManagerController getPrev() {
		return prev;
	}

}
